package com.stack.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stack.admin.mapper.AdChannelMapper;
import com.stack.admin.service.AdChannelService;
import com.stack.apis.wemedia.IWemediaClient;
import com.stack.common.utils.thread.AdminThreadLocalUtil;
import com.stack.common.utils.thread.WmThreadLocalUtil;
import com.stack.model.admin.dtos.AdChannelDto;
import com.stack.model.admin.dtos.PageQueryDto;
import com.stack.model.admin.pojos.AdChannel;
import com.stack.model.admin.pojos.AdUser;
import com.stack.model.common.dtos.PageResponseResult;
import com.stack.model.common.dtos.ResponseResult;
import com.stack.model.common.enums.AppHttpCodeEnum;
import com.stack.model.wemedia.pojos.WmChannel;
import com.stack.model.wemedia.pojos.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author llz
 * @date 2023/11/14 23:40
 * @description
 */
@Service
@Slf4j
public class AdChannelServiceImpl extends ServiceImpl<AdChannelMapper, AdChannel> implements AdChannelService {

    @Resource
    private AdChannelMapper adChannelMapper;

    @Resource
    private IWemediaClient wemediaClient;
    /**
     * 查询频道列表
     *
     * @return
     */
    @Override
    public ResponseResult getChannelList(PageQueryDto dto) {

        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }


        LambdaQueryWrapper<AdChannel> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.like(ObjectUtils.isNotEmpty(dto.getName()), AdChannel::getName, dto.getName());
        queryWrapper.eq(ObjectUtils.isNotEmpty(dto.getStatus()), AdChannel::getStatus, dto.getChannelStatus());
        queryWrapper.eq(AdChannel::getDeleted, "00");
        queryWrapper.orderByAsc(AdChannel::getId);

//        IPage page = new Page(dto.getPage(), dto.getSize());
//        IPage pageList = adChannelMapper.selectPage(page, queryWrapper);
//        log.info("数量：{}", pageList.getTotal());  // 数量=0
//        Integer count = adChannelMapper.selectCount(queryWrapper);
//        log.info("数量：{}", count); //数量正确

        IPage<AdChannel> page = new Page<>(dto.getPage(), dto.getSize());
        IPage<AdChannel> pageList = adChannelMapper.selectPage(page, queryWrapper);
        log.info("数量：{}", pageList.getTotal());

        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) pageList.getTotal());
        responseResult.setData(pageList.getRecords());
        return responseResult;
    }

    /**
     * 新增频道
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult saveChannel(AdChannelDto dto) {

        if (dto == null || dto.getName() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        AdUser adUser = AdminThreadLocalUtil.getUser();
        if (adUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        AdChannel adChannel = JSON.parseObject(JSON.toJSONString(dto), AdChannel.class);
        Date date = new Date();
        adChannel.setCreatedTime(date);
        adChannel.setIsDefault(0);
        adChannel.setDeleted("00");

        adChannelMapper.insert(adChannel);
        log.info("保存的频道id:{}", adChannel.getId());

        // 同步到自媒体端频道  TODO 需要数据库主键一致才能同步
        WmChannel wmChannel = new WmChannel();
        BeanUtils.copyProperties(adChannel, wmChannel);
        wmChannel.setIsDefault(false);
        wemediaClient.saveChannel(wmChannel);

        ResponseResult responseResult = new ResponseResult();
        responseResult.setData(adChannel.getId());
        responseResult.setErrorMessage(AppHttpCodeEnum.SUCCESS.getErrorMessage());

        return responseResult;
    }

    /**
     * 修改频道
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateChannel(AdChannelDto dto) {
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        AdUser adUser = AdminThreadLocalUtil.getUser();
        if (adUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        log.info("修改的频道id111:{}", dto.getId());
        LambdaUpdateWrapper<AdChannel> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(AdChannel::getId, dto.getId());
        updateWrapper.set(ObjectUtils.isNotEmpty(dto.getName()), AdChannel::getName, dto.getName());
        updateWrapper.set(ObjectUtils.isNotEmpty(dto.getDescription()), AdChannel::getDescription, dto.getDescription());
        updateWrapper.set(ObjectUtils.isNotEmpty(dto.getIsDefault()), AdChannel::getIsDefault, dto.getIsDefault());
        updateWrapper.set(ObjectUtils.isNotEmpty(dto.getOrd()), AdChannel::getOrd, dto.getOrd());
        updateWrapper.set(ObjectUtils.isNotEmpty(dto.getStatus()), AdChannel::getStatus, dto.getStatus());
        adChannelMapper.update(null, updateWrapper);

        log.info("修改的频道id222:{}", dto.getId());
        // 同步到自媒体端频道
        updateWmChannel(dto);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }

    private void updateWmChannel(AdChannelDto dto) {
        WmChannel wmChannel = new WmChannel();
        wmChannel.setId(dto.getId());

        if (dto.getName() != null){
            wmChannel.setName(dto.getName());
        }

        if (dto.getDescription()!= null){
            wmChannel.setDescription(dto.getDescription());
        }

        if (dto.getIsDefault()!= null){
            if (dto.getIsDefault() == 1){
                wmChannel.setIsDefault(true);
            } else {
                wmChannel.setIsDefault(false);
            }
        }

        if (dto.getOrd()!= null){
            wmChannel.setOrd(dto.getOrd());
        }

        if (dto.getStatus()!= null){
            wmChannel.setStatus(dto.getStatus());
        }

        log.info("修改的频道：{}", wmChannel);
        wemediaClient.updateChannel(wmChannel);
    }

    /**
     * 删除频道
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deleteChannel(Integer id) {
        if (ObjectUtils.isEmpty(id)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        AdUser adUser = AdminThreadLocalUtil.getUser();
        if (adUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        AdChannel channel = AdChannel.builder()
                .id(id)
                .status(false)
                .deleted("01")
                .build();

        //IService
        updateById(channel);

        //
        AdChannelDto dto = AdChannelDto.builder()
                .id(id)
                .status(false)
                .build();
        log.info("删除的频道dto:{}", dto);
        updateWmChannel(dto);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }
}
